<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/Blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/Blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/Blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/Blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/Blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/Blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/Blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="JavaScript,表单," />










<meta name="description" content="表单验证工具实现思路​ 对于表单需要校验的内容，参考element-ui和ant-design实现对是否必填、字符长度、大小、正则、类型校验。其中，类型包括integer、number、string、bool等。校验工具将会把校验结果返回。 ​ 对于所有表单数据的一次性校验，只需要传入所有的表单数据和校验规则，校验工具将会返回校验结果。 ​ 对于表单某输入项的实时校验，只需要在光标移出输入框时使用">
<meta property="og:type" content="article">
<meta property="og:title" content="表单验证工具">
<meta property="og:url" content="https://jingping-ye.github.io/Blog/2019/10/10/%E8%A1%A8%E5%8D%95%E9%AA%8C%E8%AF%81%E5%B7%A5%E5%85%B7/index.html">
<meta property="og:site_name" content="jingping.ye">
<meta property="og:description" content="表单验证工具实现思路​ 对于表单需要校验的内容，参考element-ui和ant-design实现对是否必填、字符长度、大小、正则、类型校验。其中，类型包括integer、number、string、bool等。校验工具将会把校验结果返回。 ​ 对于所有表单数据的一次性校验，只需要传入所有的表单数据和校验规则，校验工具将会返回校验结果。 ​ 对于表单某输入项的实时校验，只需要在光标移出输入框时使用">
<meta property="article:published_time" content="2019-10-10T10:01:00.000Z">
<meta property="article:modified_time" content="2020-05-14T05:56:10.962Z">
<meta property="article:author" content="jingping.ye">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="表单">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/Blog/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://jingping-ye.github.io/Blog/2019/10/10/表单验证工具/"/>





  <title>表单验证工具 | jingping.ye</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/Blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">jingping.ye</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">jingping.ye的Blog</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/Blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/Blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/Blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/Blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            标签
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://jingping-ye.github.io/Blog/Blog/2019/10/10/%E8%A1%A8%E5%8D%95%E9%AA%8C%E8%AF%81%E5%B7%A5%E5%85%B7/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="jingping.ye">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/Blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="jingping.ye">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">表单验证工具</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-10-10T18:01:00+08:00">
                2019-10-10
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2020-05-14T13:56:10+08:00">
                2020-05-14
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/Blog/categories/%E6%8A%80%E6%9C%AF/" itemprop="url" rel="index">
                    <span itemprop="name">技术</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/Blog/categories/%E6%8A%80%E6%9C%AF/%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index">
                    <span itemprop="name">前端</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  5
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="表单验证工具"><a href="#表单验证工具" class="headerlink" title="表单验证工具"></a>表单验证工具</h1><h2 id="实现思路"><a href="#实现思路" class="headerlink" title="实现思路"></a>实现思路</h2><p>​ 对于表单需要校验的内容，参考<code>element-ui</code>和<code>ant-design</code>实现对是否必填、字符长度、大小、正则、类型校验。其中，类型包括<code>integer、number、string、bool</code>等。校验工具将会把校验结果返回。</p>
<p>​ 对于所有表单数据的一次性校验，只需要传入所有的表单数据和校验规则，校验工具将会返回校验结果。</p>
<p>​ 对于表单某输入项的实时校验，只需要在光标移出输入框时使用校验工具校验。此时传入所有表单的数据、校验规则、以及该项对应的字段名。校验工具将会过滤掉 required（必输校验）。最终返回校验规则</p>
<h2 id="实现代码"><a href="#实现代码" class="headerlink" title="实现代码"></a>实现代码</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/***</span></span><br><span class="line"><span class="comment"> * (一)校验示例</span></span><br><span class="line"><span class="comment"> * let stu = &#123;name:'',phone:''&#125;;</span></span><br><span class="line"><span class="comment"> * let rules = &#123;</span></span><br><span class="line"><span class="comment"> *  name:[&#123;required:true, message:'请输入名称'&#125;, &#123;minLength:2, maxLength:5, message:'姓名长度在2-5个字符'&#125;],</span></span><br><span class="line"><span class="comment"> *  phone:[&#123;required:true, message:'请输入手机号'&#125;, &#123;pattern: /^1[34578]\d&#123;9&#125;$/,message:'请输入正确的手机号!'&#125;]</span></span><br><span class="line"><span class="comment"> * &#125;</span></span><br><span class="line"><span class="comment"> * // 校验全部表单数据</span></span><br><span class="line"><span class="comment"> * let validateRes = validateForm(stu, rules);</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * // 校验某个字段</span></span><br><span class="line"><span class="comment"> * let validateRes = validateForm(stu, rules, 'name');</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * (二)支持校验规则</span></span><br><span class="line"><span class="comment"> * 1. 是否必填 required:true|false(message是指不符合规则的提示信息))</span></span><br><span class="line"><span class="comment"> * 2. 字符长度校验 minLength:3|maxLength:10(包括3和10)</span></span><br><span class="line"><span class="comment"> * 3. 数字大小校验 min:3|max:10(包括3和10)</span></span><br><span class="line"><span class="comment"> * 4. 正则校验 pattern:/^1[34578]\d&#123;9&#125;$/ (注意表单输入的都是字符串)</span></span><br><span class="line"><span class="comment"> * 5. 类型校验 type:"integer"|"number"|"string"|"bool"</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/************************ 校验策略对象 ******************************/</span></span><br><span class="line"><span class="keyword">const</span> strategies = &#123;</span><br><span class="line">  required: <span class="function"><span class="keyword">function</span> (<span class="params">val, isRequired</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (isRequired) &#123;</span><br><span class="line">      <span class="keyword">return</span> val.length &gt; <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">  &#125;,</span><br><span class="line">  minLength: <span class="function"><span class="keyword">function</span> (<span class="params">val, minLen</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (val.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> val.length &gt;= minLen;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">  &#125;,</span><br><span class="line">  maxLength: <span class="function"><span class="keyword">function</span> (<span class="params">val, maxLen</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (val.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> val.length &lt;= maxLen;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">  &#125;,</span><br><span class="line">  min: <span class="function"><span class="keyword">function</span> (<span class="params">val, minNum</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (val.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="built_in">Number</span>(val) &gt;= minNum;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">  &#125;,</span><br><span class="line">  max: <span class="function"><span class="keyword">function</span> (<span class="params">val, maxNum</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (val.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="built_in">Number</span>(val) &lt;= maxNum;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">  &#125;,</span><br><span class="line">  pattern: <span class="function"><span class="keyword">function</span> (<span class="params">val, patternRule</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (val.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">      <span class="keyword">return</span> patternRule.test(val);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">  &#125;,</span><br><span class="line">  type: <span class="function"><span class="keyword">function</span> (<span class="params">val, valType</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (val.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">      <span class="keyword">let</span> isRequiredValType = <span class="literal">false</span>;</span><br><span class="line">      <span class="keyword">switch</span> (valType) &#123;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"integer"</span>:</span><br><span class="line">          <span class="keyword">if</span> (<span class="built_in">parseInt</span>(val) === <span class="built_in">Number</span>(val) &amp;&amp; val.indexOf(<span class="string">"."</span>) === <span class="number">-1</span>) &#123;</span><br><span class="line">            isRequiredValType = <span class="literal">true</span>;</span><br><span class="line">          &#125;</span><br><span class="line">          <span class="keyword">break</span>;</span><br><span class="line">        <span class="keyword">case</span> <span class="string">"number"</span>:</span><br><span class="line">          <span class="keyword">if</span> (<span class="built_in">parseFloat</span>(val).toString() !== <span class="string">"NaN"</span>) &#123;</span><br><span class="line">            isRequiredValType = <span class="literal">true</span>;</span><br><span class="line">          &#125;</span><br><span class="line">        <span class="keyword">default</span>:</span><br><span class="line">          <span class="keyword">if</span> (<span class="keyword">typeof</span> val === valType) &#123;</span><br><span class="line">            isRequiredValType = <span class="literal">true</span>;</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> isRequiredValType;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">  &#125;,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*******************************  Validator类 ***************************************/</span></span><br><span class="line"><span class="keyword">let</span> Validator = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">this</span>.cache = [];</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 挑选校验规则</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">Validator.prototype.add = <span class="function"><span class="keyword">function</span> (<span class="params">rules</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> _this = <span class="keyword">this</span>;</span><br><span class="line">  rules.forEach(<span class="function"><span class="keyword">function</span> (<span class="params">item</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i <span class="keyword">in</span> item) &#123;</span><br><span class="line">      <span class="keyword">if</span> (strategies.hasOwnProperty(i)) &#123;</span><br><span class="line">        <span class="keyword">const</span> validateGroup = &#123;&#125;;</span><br><span class="line">        validateGroup[i] = item[i];</span><br><span class="line">        validateGroup[<span class="string">"message"</span>] = item[<span class="string">"message"</span>];</span><br><span class="line">        _this.cache.push(validateGroup);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 开始校验</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">Validator.prototype.start = <span class="function"><span class="keyword">function</span> (<span class="params">curData</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> _cache = <span class="keyword">this</span>.cache;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; _cache.length; i++) &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> j <span class="keyword">in</span> _cache[i]) &#123;</span><br><span class="line">      <span class="keyword">if</span> (strategies.hasOwnProperty(j)) &#123;</span><br><span class="line">        <span class="keyword">if</span> (!strategies[j](curData, <span class="keyword">this</span>.cache[i][j])) &#123;</span><br><span class="line">          <span class="keyword">return</span> &#123; <span class="attr">flag</span>: <span class="literal">false</span>, <span class="attr">message</span>: <span class="keyword">this</span>.cache[i][<span class="string">"message"</span>] &#125;;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> &#123; <span class="attr">flag</span>: <span class="literal">true</span> &#125;;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/************************************ 环境调用 **************************************/</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 深拷贝对象数组</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;arr&#125;</span> </span>source 数组</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> deepCopy = <span class="function"><span class="keyword">function</span> (<span class="params">source</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> arr = source.map(<span class="function"><span class="keyword">function</span> (<span class="params">item</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> obj = &#123;&#125;;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i <span class="keyword">in</span> item) &#123;</span><br><span class="line">      obj[i] = item[i];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> obj;</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> arr;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 过滤子项规则，去除required</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;obj&#125;</span> </span>allRules 所有规则</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;string&#125;</span> </span>prop 需要获取的规则的子项</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> getItemRules = <span class="function"><span class="keyword">function</span> (<span class="params">allRules, prop</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">let</span> ValidateItemRules = deepCopy(allRules[prop]);</span><br><span class="line">  <span class="keyword">let</span> validateItemRulesWithoutRequired = ValidateItemRules.filter(<span class="function"><span class="keyword">function</span> (<span class="params">item</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> !item.hasOwnProperty(<span class="string">"required"</span>);</span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">return</span> validateItemRulesWithoutRequired;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 获取表单中的数据子项</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;obj&#125;</span> </span>allData 所有表单数据</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;string&#125;</span> </span>prop 需要获取的表单子项</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> getItemData = <span class="function"><span class="keyword">function</span> (<span class="params">allData, prop</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> data = <span class="built_in">JSON</span>.parse(<span class="built_in">JSON</span>.stringify(allData));</span><br><span class="line">  <span class="keyword">return</span> data[prop].toString().trim();</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;string&#125;</span> </span>data 校验数据</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;obj&#125;</span> </span>rules 校验规则</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> runValidator = <span class="function"><span class="keyword">function</span> (<span class="params">data, rules</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> validator = <span class="keyword">new</span> Validator();</span><br><span class="line">  validator.add(rules);</span><br><span class="line">  <span class="keyword">return</span> validator.start(data);</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 校验表单</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;obj&#125;</span> </span>data 表单数据</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;obj&#125;</span> </span>validateRules 表单校验规则</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;string&#125;</span> </span>prop 需要校验的子项字段</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">const</span> validateForm = <span class="function"><span class="keyword">function</span> (<span class="params">data, validateRules, prop</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (prop) &#123;</span><br><span class="line">    <span class="keyword">const</span> curData = getItemData(data, prop);</span><br><span class="line">    <span class="keyword">const</span> rules = getItemRules(validateRules, prop);</span><br><span class="line">    <span class="keyword">if</span> (rules) &#123;</span><br><span class="line">      <span class="keyword">const</span> validateRes = runValidator(curData, rules);</span><br><span class="line">      <span class="keyword">if</span> (!validateRes.flag) &#123;</span><br><span class="line">        <span class="keyword">return</span> &#123; <span class="attr">flag</span>: <span class="literal">false</span>, <span class="attr">name</span>: prop, <span class="attr">data</span>: curData, <span class="attr">message</span>: validateRes.message &#125;;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> &#123; <span class="attr">flag</span>: <span class="literal">true</span> &#125;;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> i <span class="keyword">in</span> data) &#123;</span><br><span class="line">      <span class="keyword">const</span> rules = validateRules[i];</span><br><span class="line">      <span class="keyword">const</span> curData = data[i].toString().trim();</span><br><span class="line">      <span class="keyword">if</span> (rules) &#123;</span><br><span class="line">        <span class="keyword">const</span> validateRes = runValidator(curData, rules);</span><br><span class="line">        <span class="keyword">if</span> (!validateRes.flag) &#123;</span><br><span class="line">          <span class="keyword">return</span> &#123; <span class="attr">flag</span>: <span class="literal">false</span>, <span class="attr">name</span>: i, <span class="attr">data</span>: data[i], <span class="attr">message</span>: validateRes.message &#125;;</span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> &#123; <span class="attr">flag</span>: <span class="literal">true</span> &#125;;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports = validateForm;</span><br></pre></td></tr></table></figure>

<p>​</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/Blog/tags/JavaScript/" rel="tag"># JavaScript</a>
          
            <a href="/Blog/tags/%E8%A1%A8%E5%8D%95/" rel="tag"># 表单</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/Blog/2019/09/28/%E9%87%91%E8%9E%8D%E5%A4%A7%E6%95%B0%E9%AB%98%E7%B2%BE%E5%BA%A6%E8%AE%A1%E7%AE%97%E8%A7%A3%E5%86%B3%E6%96%B9%E6%A1%88/" rel="next" title="金融大数高精度计算解决方案">
                <i class="fa fa-chevron-left"></i> 金融大数高精度计算解决方案
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/Blog/2019/10/14/%E5%B9%BF%E5%B7%9E%E5%87%BA%E5%B7%AE%E6%80%BB%E7%BB%93/" rel="prev" title="广州出差总结">
                广州出差总结 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">jingping.ye</p>
              <p class="site-description motion-element" itemprop="description">jingping.ye的Blog|文章</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/Blog/archives/">
              
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/Blog/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/Blog/tags/index.html">
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/yourname" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:yourname@gmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://plus.google.com/yourname" target="_blank" title="Google">
                      
                        <i class="fa fa-fw fa-google"></i>Google</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://twitter.com/yourname" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-twitter"></i>Twitter</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.facebook.com/yourname" target="_blank" title="FB Page">
                      
                        <i class="fa fa-fw fa-facebook"></i>FB Page</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://vk.com/yourname" target="_blank" title="VK Group">
                      
                        <i class="fa fa-fw fa-vk"></i>VK Group</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://stackoverflow.com/yourname" target="_blank" title="StackOverflow">
                      
                        <i class="fa fa-fw fa-stack-overflow"></i>StackOverflow</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://youtube.com/yourname" target="_blank" title="YouTube">
                      
                        <i class="fa fa-fw fa-youtube"></i>YouTube</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://instagram.com/yourname" target="_blank" title="Instagram">
                      
                        <i class="fa fa-fw fa-instagram"></i>Instagram</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="skype:yourname?call|chat" target="_blank" title="Skype">
                      
                        <i class="fa fa-fw fa-skype"></i>Skype</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#表单验证工具"><span class="nav-number">1.</span> <span class="nav-text">表单验证工具</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#实现思路"><span class="nav-number">1.1.</span> <span class="nav-text">实现思路</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#实现代码"><span class="nav-number">1.2.</span> <span class="nav-text">实现代码</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">jingping.ye</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">15k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Mist</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/Blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/Blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/Blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/Blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/Blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/Blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/Blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/Blog/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/Blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/Blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/Blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
